var tsc = require("../util/ble/tsc.js");
// var esc = require('../components/gprint/esc.js')
var app = getApp();

var jpPrinterObj = {
  createNew: function () {
    var list = [];
    var numList = [];
    var j = 0;

    for (var i = 20; i < 200; i += 10) {
      list[j] = i;
      j++;
    }

    for (var i = 1; i < 10; i++) {
      numList[i - 1] = i;
    }
    jpPrinterObj.init = function () {};
    /*
			打印测试页
		*/
    (jpPrinterObj.testPrint = function () {
     let deviceId = uni.getStorageSync('deviceId');
     let serviceId = uni.getStorageSync('writeServiceId');
     let characteristicId = uni.getStorageSync('writeCharaterId');
      var command = tsc.jpPrinter.createNew();
      command.setCls();
      command.setSelfTest();
      command.setPagePrint();

      jpPrinterObj.prepareSend(
        deviceId,
        serviceId,
        characteristicId,
        command.getData()
      );
    }),
      (jpPrinterObj.labelPrint = function (imageData) {
     let deviceId = uni.getStorageSync('deviceId');
     let serviceId = uni.getStorageSync('writeServiceId');
     let characteristicId = uni.getStorageSync('writeCharaterId');
        let userInfo = app.globalData.userInfo;
        let mchPrint = Number(userInfo["mchPrint"]);
        let x = 0;
        let y = 0;
        var command = tsc.jpPrinter.createNew();
        y = 30;
        command.setGap(0);
        command.setCls();

        command.setBar(50, y + 160, 500, 2);

        command.setBitmap(150, y + 150, 0, imageData);

        command.setPagePrint();
        jpPrinterObj.prepareSend(
          deviceId,
          serviceId,
          characteristicId,
          command.getData()
        );
      }),
      (jpPrinterObj.printData = function (data) {
        let deviceId = uni.getStorageSync('deviceId');
        let serviceId = uni.getStorageSync('writeServiceId');
        let characteristicId = uni.getStorageSync('writeCharaterId');
        let userInfo = app.globalData.userInfo;
        let mchPrint = Number(userInfo["mchPrint"]);
        let x = 0;
        let y = 0;
        var command = tsc.jpPrinter.createNew();
        let longTemp = [...data.ShipmentList, ...data.returnList].length;
        y = 50;
		let temp = 0;
		if(data.ShipmentList.length==0||data.returnList.length==0){
			temp=103
		}else{
			temp=123
		}
        command.setSize(70,7 * longTemp + temp );
        // console.log(30 * longTemp + 50);
        command.setGap(0);
        command.setCls();
        command.setText(100, y, "TSS24.BF2", 2, 2, data.title);
        command.setText(50, (y += 70), "TSS24.BF2", 1, 1, `客户:${data.cname}`);
        command.setText(
          50,
          (y += 32),
          "TSS24.BF2",
          1,
          1,
          `下单时间:${data.orderTime}`
        );
        command.setBar(50, (y += 60), 500, 2);

        var indexResult = 0;
        y = 224;
        if (data.ShipmentList.length > 0) {
          if (mchPrint == 4) {
            command.setText(50, y, "TSS24.BF2", 1, 1, "货号");
            command.setText(180, y, "TSS24.BF2", 1, 1, "单价");
            command.setText(280, y, "TSS24.BF2", 1, 1, "数量");
            command.setText(380, y, "TSS24.BF2", 1, 1, "金额");
          } else {
            command.setText(50, y, "TSS24.BF2", 1, 1, "货号");
            command.setText(180, y, "TSS24.BF2", 1, 1, "数量");
          }
          command.setBar(50, (y += 32), 500, 2);
          if (mchPrint == 4) {
            data.ShipmentList.forEach((item, index) => {
              indexResult = index + 1;
              command.setText(50, (y += 24), "TSS24.BF2", 1, 1, item.proId);
              command.setText(180, y, "TSS24.BF2", 1, 1, item.realPrice);
              command.setText(300, y, "TSS24.BF2", 1, 1, item.orderNum);
              var orderPriceTotal =
                Math.floor(item.realPrice * item.orderNum * 100) / 100;
              command.setText(380, y, "TSS24.BF2", 1, 1, orderPriceTotal);
              command.setBar(50, (y += 32), 500, 2);
            });
          } else {
            data.ShipmentList.forEach((item, index) => {
              indexResult = index + 1;
              command.setText(50, (y += 24), "TSS24.BF2", 1, 1, item.proId);
              // command.setText(180, y+30*indexResult, "TSS24.BF2", 1, 1, item.realPrice)
              command.setText(180, y, "TSS24.BF2", 1, 1, item.orderNum);
              // command.setText(380, y+30*indexResult, "TSS24.BF2", 1, 1, item.realPrice * item.orderNum)
              command.setBar(50, (y += 32), 500, 2);
            });
          }
          command.setText(50, (y += 24), "TSS24.BF2", 1, 1, "小计");
          if (mchPrint == 4) {
            command.setText(
              300,
              y,
              "TSS24.BF2",
              1,
              1,
              data.ShipmentList.reduce((pre, cur) => {
                return pre + cur.orderNum;
              }, 0)
            );
            var orderPriceTotal = data.ShipmentList.reduce((pre, cur) => {
              return pre + cur.orderNum * cur.realPrice;
            }, 0);
            orderPriceTotal = Math.floor(orderPriceTotal * 100) / 100;
            command.setText(380, y, "TSS24.BF2", 1, 1, orderPriceTotal);
          } else {
            command.setText(
              180,
              y,
              "TSS24.BF2",
              1,
              1,
              data.ShipmentList.reduce((pre, cur) => {
                return pre + cur.orderNum;
              }, 0)
            );
          }
        }

        if (data.returnList.length > 0) {
				let p = 0;
			if(data.ShipmentList.length==0){
				p = 0
			}else{
				p = 80
			}
			
          if (mchPrint == 4) {
            command.setText(50, (y += p), "TSS24.BF2", 1, 1, "退货货号");
            command.setText(180, y, "TSS24.BF2", 1, 1, "单价");
            command.setText(300, y, "TSS24.BF2", 1, 1, "数量");
            command.setText(380, y, "TSS24.BF2", 1, 1, "金额");
          } else {
            command.setText(50, (y += p), "TSS24.BF2", 1, 1, "退货货号");
            // command.setText(180, y+30, "TSS24.BF2", 1, 1, "单价")
            command.setText(180, y, "TSS24.BF2", 1, 1, "数量");
            // command.setText(380, y+30, "TSS24.BF2", 1, 1, "金额")
          }
          command.setBar(50, (y += 32), 500, 2);
          if (mchPrint == 4) {
            data.returnList.forEach((item, index) => {
              indexResult = index + 2;
              command.setText(50, (y += 24), "TSS24.BF2", 1, 1, item.proId);
              command.setText(180, y, "TSS24.BF2", 1, 1, item.realPrice);
              command.setText(300, y, "TSS24.BF2", 1, 1, item.orderNum);
              command.setText(
                380,
                y,
                "TSS24.BF2",
                1,
                1,
                (item.realPrice * 1000 * item.orderNum * 1000) / 1000000
              );

              command.setBar(50, (y += 32), 500, 2);
            });
          } else {
            data.returnList.forEach((item, index) => {
              indexResult = index + 2;
              command.setText(50, (y += 24), "TSS24.BF2", 1, 1, item.proId);
              // command.setText(180, y+30*indexResult, "TSS24.BF2", 1, 1, item.realPrice)
              command.setText(180, y, "TSS24.BF2", 1, 1, item.orderNum);
              // command.setText(380, y+30*indexResult, "TSS24.BF2", 1, 1, item.realPrice * item.orderNum)

              command.setBar(50, (y += 32), 500, 2);
            });
          }
          command.setText(50, (y += 24), "TSS24.BF2", 1, 1, "小计");
          if (mchPrint == 4) {
            command.setText(
              300,
              (y += 24),
              "TSS24.BF2",
              1,
              1,
              data.returnList.reduce((pre, cur) => {
                return pre + cur.orderNum;
              }, 0)
            );
            var orderPriceTotal = data.returnList.reduce((pre, cur) => {
              return pre + cur.orderNum * cur.realPrice;
            }, 0);
            orderPriceTotal = Math.floor(orderPriceTotal * 100) / 100;
            command.setText(380, y, "TSS24.BF2", 1, 1, orderPriceTotal);
          } else {
            command.setText(
              180,
              y,
              "TSS24.BF2",
              1,
              1,
              data.returnList.reduce((pre, cur) => {
                return pre + cur.orderNum;
              }, 0)
            );
          }
        }

        var totalPrice = Math.floor(data.totalPrice * 100) / 100;
        y += 80;
        if (mchPrint == 4) {
          command.setText(50, y, "TSS24.BF2", 1, 1, `总金额:${totalPrice}`);
        }

        // y = y+30*(indexResult+1) + 90;

        command.setText(
          50,
          (y += 32),
          "TSS24.BF2",
          1,
          1,
          `地址:${
            app.globalData.userInfo.mchAddress
              ? app.globalData.userInfo.mchAddress
              : "未填写"
          }`
        );
        command.setText(
          50,
          (y += 32),
          "TSS24.BF2",
          1,
          1,
          `电话:${
            app.globalData.userInfo.mchTel
              ? app.globalData.userInfo.mchTel
              : "未填写"
          }`
        );
        command.setText(50, (y += 32), "TSS24.BF2", 1, 1, `客户签名`);
        // console.log('data.imageData'+data.imageData);
        if (data.imageData != null) {
          command.setBitmap(150, (y += 32), 0, data.imageData);
        }

        command.setText(
          30,
          (y += 160),
          "TSS24.BF2",
          1,
          1,
          `魔简erp技术支持   Tel：15870660763`
        );
        command.setText(
          30,
          (y += 32),
          "TSS24.BF2",
          1,
          1,
          `==============================================`
        );
        command.setPagePrint();
        jpPrinterObj.prepareSend(
          deviceId,
          serviceId,
          characteristicId,
          command.getData()
        );
      });

    jpPrinterObj.prepareSend = function (
      deviceId,
      serviceId,
      characteristicId,
      uint8Array
    ) {
      var uint8Buf = Array.from(uint8Array);
      // console.log(deviceId, serviceId, characteristicId, uint8Array)

      function split_array(datas, size) {
        var result = {};
        var j = 0;
        for (var i = 0; i < datas.length; i += size) {
          result[j] = datas.slice(i, i + size);
          j++;
        }
        return result;
      }
      var sendloop = split_array(uint8Buf, 20);

      function realWriteData(sendloop, i) {
        var data = sendloop[i];
        if (typeof data == "undefined") {
          return;
        }
        var buffer = new ArrayBuffer(data.length);
        var dataView = new DataView(buffer);
        for (var j = 0; j < data.length; j++) {
          dataView.setUint8(j, data[j]);
        }
		// #ifdef APP-PLUS
		plus.bluetooth.writeBLECharacteristicValue({
		  deviceId,
		  serviceId,
		  characteristicId,
		  value: buffer,
		  success(res) {
		    // console.log(res,'成功')
		    setTimeout(() => {
		      realWriteData(sendloop, i + 1);
		    }, 10);
		  },
		  fail(res) {
		    console.log(res, "失败");
		  },
		});
		// #endif
		// #ifdef MP-WEIXIN
		uni.writeBLECharacteristicValue({
		  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
		  deviceId,
		  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		  serviceId,
		  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		  characteristicId,
		  // 这里的value是ArrayBuffer类型
		  value: buffer,
		  success(res) {
			  console.log("success");
		    setTimeout(() => {
		      realWriteData(sendloop, i + 1);
		    }, 10);
		  },
		  fail(e){
			  console.log("fail",e);
		  }
		})
		// #endif
        
      }
      var i = 0;
      realWriteData(sendloop, i);
    };
    return jpPrinterObj;
  },
};
module.exports.jpPrinterObj = jpPrinterObj;
